import { _decorator, Component, Node } from 'cc';
import Singleton from '../Base/Singleton';
const { ccclass, property } = _decorator;

interface IEvent {
    func: Function,
    context: any
}


/**事件管理器 */
export default class EventManager extends Singleton {

    static get Instance() {
        return super.getInstance<EventManager>();
    }

    private eventDic: Map<string, Array<IEvent>> = new Map();
    /** 绑定事件 */
    on(eventName: string, func: Function, context: any) {
        if (this.eventDic.has(eventName)) {
            this.eventDic.get(eventName)?.push({ func, context });
        } else {
            this.eventDic.set(eventName, [{ func, context }]);
        }
    }

    /**解绑事件 */
    off(eventName: string, func: Function) {
        if (this.eventDic.has(eventName)) {
            const index = this.eventDic.get(eventName).findIndex(i => i.func === func)
            index > -1 && this.eventDic.get(eventName).splice(index, 1);
        }
    }
    
    /** 触发事件 */
    emit(eventName: string, ...args: any[]) {
        if (this.eventDic.has(eventName)) {
            this.eventDic.get(eventName).forEach(({ func, context }) => {
                context ? func.apply(context, args) : func(...args)
            });
        }
    }

    /** 清空事件 */
    clear() {
        this.eventDic.clear();
    }

}